<template>
  <el-form :model="dataForm" :rules="rules" label-position="top" class="form-box" ref="dataFormRef" @keyup.enter="dataFormSubmitHandle()"
    label-width="120px">
    <el-row :gutter="20">
      <el-col :span="8">
        <el-form-item prop="name" label="周边名称">
          <el-input v-model="dataForm.name" placeholder="请输入"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item prop="typeId" label="周边类型">
          <el-select v-model="dataForm.typeId" clearable placeholder="请选择">
            <el-option :value="item.id" :label="item.text" v-for="(item, index) in merchTypeList"
              :key="index"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item prop="deptId" label="出品基地">
          <el-select v-model="dataForm.deptId" clearable placeholder="请选择">
            <el-option :value="item.id" :label="item.name" v-for="(item, index) in deptList" :key="index"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="8">
        <el-form-item prop="projectIds" label="关联研学">
          <el-select v-model="dataForm.projectIds" multiple clearable placeholder="请选择">
            <el-option :value="item.id" :label="item.name" v-for="(item, index) in projectList"
              :key="index"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>
    <el-form-item prop="visualsList" label="周边图（9图）">
      <el-upload v-model:file-list="dataForm.visualsList" :action="url" list-type="picture-card" :limit="9"
        :on-preview="handlePictureCardPreview" :on-change="handleChange" :on-remove="handleRemove">
        <el-icon>
          <Plus />
        </el-icon>
      </el-upload>
    </el-form-item>
    <el-form-item prop="intro" label="周边简介">
      <el-input v-model="dataForm.intro" :autosize="{ minRows: 2, maxRows: 6 }" type="textarea" placeholder="请输入" />
    </el-form-item>
    <el-form-item prop="buyUrl" label="周边购买链接">
      <el-input v-model="dataForm.buyUrl" placeholder="请输入" />
    </el-form-item>
    <el-form-item class="footer-btn">
      <el-button @click="cancelHandle()">取消</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">保存</el-button>
    </el-form-item>
  </el-form>
  <el-dialog class="image-dialog" v-model="dialogVisible">
    <el-image style="width: 60vw; height: 60vh" :src="dialogImageUrl" fit="scale-down" />
  </el-dialog>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from "vue";
import baseService from "@/service/baseService";
import { ElMessage, UploadProps } from "element-plus";
import app from "@/constants/app";
import { getToken } from "@/utils/cache";
import { useRoute, useRouter } from "vue-router";

const route = useRoute();
const router = useRouter();
const dataFormRef = ref();
const merchTypeList = ref<any[]>([]);
const projectList = ref<any[]>([]);
const deptList = ref<any[]>([]);
const url = ref();
const dialogImageUrl = ref('')
const dialogVisible = ref(false)

const dataForm = reactive({
  id: "",
  name: "",
  typeId: "",
  deptId: "",
  projectIds: "",
  visuals: [] as any[],
  visualsList: [] as any[],
  intro: "",
  buyUrl: "",
});

const rules = ref({
  name: [{ required: true, message: "必填项不能为空", trigger: "blur" }],
  typeId: [{ required: true, message: "必填项不能为空", trigger: "change" }],
  deptId: [{ required: true, message: "必填项不能为空", trigger: "change" }],
  visualsList: [{ required: true, message: "必填项不能为空", trigger: "blur" }],
});

const init = () => {
  dataForm.id = "";
  url.value = `${app.api}/sys/oss/upload?token=${getToken()}`;

  // 重置表单数据
  if (dataFormRef.value) {
    dataFormRef.value.resetFields();
  }

  Promise.all([getMerchTypeList(), getProjectList(), getDeptList()]).then(() => {
    if (route.query?.id) {
      getInfo(`${route.query?.id}`);
    }
  });
};

// 获取信息
const getInfo = (id: string) => {
  baseService.get(`/study/merch/${id}`).then((res) => {
    Object.assign(dataForm, res.data);
  });
};

// 获取周边类型
const getMerchTypeList = () => {
  return baseService.get("/study/merch/type/select", {}).then((res) => {
    if (res.code !== 0) {
      return ElMessage.error(res.msg);
    }
    merchTypeList.value = res.data;
  });
};

// 获取项目列表
const getProjectList = () => {
  return baseService.get("/study/event/page", { page: 1, limit: 100 }).then((res) => {
    if (res.code !== 0) {
      return ElMessage.error(res.msg);
    }
    projectList.value = res.data.list;
  });
};

// 获取学校列表
const getDeptList = () => {
  return baseService.get("/study/dept/page", { type: 'BASE' }).then((res) => {
    if (res.code !== 0) {
      return ElMessage.error(res.msg);
    }
    deptList.value = res.data.list;
  });
};

const handleRemove: UploadProps['onRemove'] = () => {
  dataForm.visuals = dataForm.visualsList.map((item) => item.id);
};

const handleChange: UploadProps['onChange'] = (uploadFile, uploadFiles) => {
  const visualsList = uploadFiles.map((item) => {
    const res: any = item.response;
    return {
      id: res?.data.id,
      url: res?.data.src,
    }
  })

  dataForm.visualsList = visualsList;
  dataForm.visuals = dataForm.visualsList.map((item) => item.id);
};

const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!
  dialogVisible.value = true
};

// 表单提交
const dataFormSubmitHandle = () => {
  dataFormRef.value.validate((valid: boolean) => {
    if (!valid) {
      return false;
    }
    (!dataForm.id ? baseService.post : baseService.put)('/study/merch', {
      ...dataForm,
    }).then((res) => {
      ElMessage.success({
        message: "成功",
        duration: 500,
        onClose: () => {
          router.push('/study/merch');
        }
      });
    });
  });
};

const cancelHandle = () => {
  router.go(-1);
};

onMounted(() => {
  init();
})
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 150px;
  height: 150px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 150px;
  height: 150px;
  text-align: center;
}

.image-dialog {
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
